/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package com.iss.examsys.ejb;

import com.iss.examsys.entity.LecturerModule;
import com.iss.examsys.entity.Module;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

/**
 *
 * @author Quek Ting Hong
 */
@Stateless
public class ModuleBean {
    @PersistenceContext EntityManager em;
    
    public Module findModuleById(Long id){
        
        Module module = em.find(Module.class, id);
        
        return module;
    }
    
    public List<Module> findAllModule(){
        TypedQuery<Module> result = em.createNamedQuery("Module.findAll", Module.class);
        
        return result.getResultList();
    }
    
    public List<Module> findModulesByLecturerId(String userId){

    List<Module> resultList = em.createNativeQuery("select m.* from lecturer_module lm, module m where m.ID = lm.MODULE_ID and lm.LECTURER_ID = ?")
            .setParameter(1, userId).getResultList();

    return resultList;
    }
 
    public List<Module> findModulesByLecturerId1(long userId) {
        TypedQuery<Module> result = em.createNamedQuery("Module.findByLectureId", Module.class);  
        result.setParameter("lectureid", userId);
        return result.getResultList();
    }
     
    
    public void createModule(Module module){
        em.persist(module);
    }
    
    public List<Module> findModuleByCode(String code){
        TypedQuery<Module> result = em.createNamedQuery("Module.findByCode", Module.class);
        result.setParameter("code", code);
        return result.getResultList();
    }
    
    public List<Module> findModuleByCode(String code, Long filterBy){
        TypedQuery<Module> result = em.createNamedQuery("Module.findByCodeFilterId", Module.class);
        result.setParameter("code", code);
        result.setParameter("id", filterBy);
        return result.getResultList();
    }
    
    public void deleteModule(List<Module> modules){
        if(modules!=null && !modules.isEmpty()){
            for(Module module : modules){
                Module remModule = em.merge(module);
                em.remove(remModule);
            }
        }
    }
    
    public Module findModuleByName(String name){
        
        TypedQuery<Module> result = em.createNamedQuery("Module.findByName", Module.class);
        result.setParameter("name", name);    
        
        List<Module> list = result.getResultList();
        
        if(list == null)
            return new Module();
        return list.get(0);
    }
    
    public void editModule(Module module){
        em.merge(module);        
    }
}
